package com.fwzc.giuseppe.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.os.Environment;
import android.text.TextPaint;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * 自定义辅助类
 *
 */
@SuppressWarnings("deprecation")
public class Utils {

	/**
	 * 获取map的key
	 * 
	 * @param map
	 * @return String[]字符数组
	 */
	public static String[] getkey(Map<String, ?> map) {

		Set<String> keySet = map.keySet(); // key的set集合
		Iterator<String> it = keySet.iterator();
		List<String> list = new ArrayList<String>();

		while (it.hasNext()) {
			String k = (String) it.next(); // key
			// Object v = map.get(k); //value
			// System.out.println("K:" + k + " V:" + v);

			list.add(k);
		}
		String[] key = list.toArray(new String[1]);

		return key;
	}

	/**
	 * 获取map的value
	 * 
	 * @param map
	 * @return List<String>
	 */
	@SuppressWarnings("rawtypes")
	public static List getValue(Map<String, String> map) {

		Set<String> keySet = map.keySet(); // key的set集合
		Iterator<String> it = keySet.iterator();
		List<String> list = new ArrayList<String>();

		while (it.hasNext()) {
			String k = (String) it.next(); // key
			String v = map.get(k); // value
			// System.out.println("K:" + k + " V:" + v);

			list.add(v);
		}

		return list;
	}

	/**
	 * 遍历map中的value
	 * 
	 * @param map
	 * @return String[]
	 */
	public static String[] getValues(Map<String, String> map) {

		Set<String> keySet = map.keySet(); // key的set集合
		Iterator<String> it = keySet.iterator();
		List<String> list = new ArrayList<String>();

		while (it.hasNext()) {
			String k = (String) it.next(); // key
			String v = map.get(k); // value
			// System.out.println("K:" + k + " V:" + v);

			list.add(v);
		}
		String[] values = list.toArray(new String[1]);

		return values;
	}

	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */

	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	/**
	 * 获取屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	/**
	 * 获取屏幕像素
	 * 
	 * @param context
	 * @return
	 */
	public static float getScreenDensity(Context context) {
		try {
			DisplayMetrics dm = new DisplayMetrics();
			WindowManager manager = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			manager.getDefaultDisplay().getMetrics(dm);
			return dm.density;
		} catch (Exception ex) {

		}
		return 1.0f;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 * 
	 * @param context
	 * @param dpValue
	 * @return int
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 * 
	 * @param context
	 * @param pxValue
	 * @return int
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 检查是否存在SDCard
	 * 
	 * @return boolean
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * 判断是否为网址
	 * 
	 * @param url
	 * @return boolean
	 */

	public static boolean isUrl(String url) {
		Pattern pattern = Pattern.compile("^http://.+$");


		Matcher isNum = pattern.matcher(url);

		if (!isNum.matches()) {

			return false;

		}

		return true;

	}
	
	
	/**
	 * 
	 * 隐藏名字首字符
	 * 
	 * @param realname
	 * @return String
	 */

	public static String hintName(String realname) {

		String name=realname.replaceAll("^.", "*");
		
		return name;
	}
	
	
	/**
	 * 
	 * 隐藏身份证银行卡中间部分
	 * 
	 * @param banknum
	 * @return String
	 */

	public static String hintCardnum(String cardnum) {

		String num=cardnum.replaceAll("(?<=\\d{4})\\d(?=\\d{4})", "*");
		
		return num;
	}
	
	/**
	 * 
	 * 隐藏电话中间部分
	 * 
	 * @param phone
	 * @return String
	 */

	public static String hintPhonenum(String phone) {

		String num=phone.replaceAll("(?<=\\d{3})\\d(?=\\d{3})", "*");
		
		return num;
	}

	/**
	 * 
	 * 判断是否为中文开头
	 * 
	 * @param str
	 * @return boolean
	 */

	public static boolean isChinese(String str) {

		Pattern pattern = Pattern.compile("^[\u4E00-\u9FA5]+$");

		Matcher isChinese = pattern.matcher(str);

		if (!isChinese.matches()) {

			return false;

		}
		return true;
	}
	

	/**
	 * 
	 * 判断是否包含中文
	 * 
	 * @param str
	 * @return boolean
	 */

	public static boolean isContainsChinese(String str) {

		Pattern pattern = Pattern.compile("[\u4E00-\u9FA5]");

		Matcher isChinese = pattern.matcher(str);

		if (!isChinese.find()) {

			return false;

		}
		return true;
	}

	/**
	 * 检测字符串中只能包含：中文、数字、下划线(_)、横线(-)
	 * @param sequence
	 * @return boolean
	 */
	public static boolean checkNickname(String sequence) {
        final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_]";
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(sequence);
        return !matcher.find();
    } 
	
	
	/**
	 * 检测字符串中是否包含汉字
	 * @param sequence
	 * @return boolean
	 */
	public static boolean checkChinese(String sequence) {
        final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";
        boolean result = false;
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(sequence);
        result = matcher.find();
        return result;
    }
	
	
	/**
	 * 检查有没有应用程序来接受处理你发出的intent
	 * @param context
	 * @param action
	 * @return boolean
	 */
	public static boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }
	
	/**
	 * 计算字宽
	 * @param text
	 * @param Size
	 * @return
	 */
	public static float GetTextWidth(String text, float Size) {
        TextPaint FontPaint = new TextPaint();
        FontPaint.setTextSize(Size);
        return FontPaint.measureText(text);
    }
	
	
	/**
	 * 
	 * 是否为合法密码
	 * @param pwd 密码
	 * @param minlen 最少长度
	 * @param maxlen 最大长度
	 * @return boolean
	 */
	public static boolean isPwds(String pwd,int minlen,int maxlen) {
		//两个都正确
//		String reg = "^(?![0-9]*$)(?![a-zA-Z]*$)[a-zA-Z0-9]{"+minlen+","+maxlen+"}$";
		String reg = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{"+minlen+","+maxlen+"}$";
		Pattern pattern = Pattern.compile(reg);
		Matcher m = pattern.matcher(pwd);

		return m.matches();

	}
	
	
	/**
	 * 
	 * 是否为合法密码
	 * @param pwd 密码
	 * @param minlen 最少长度
	 * @param maxlen 最大长度
	 * @return boolean
	 */
	public static boolean pwdLenth(String pwd,int minlen,int maxlen) {
		//两个都正确
		if(pwd.length()>=minlen&&pwd.length()<=maxlen){
			return true;
		}else{
			return false;
		}

	}
	
	/**
	 * 是否为手机号(匹配11位)
	 * 
	 * @param phone
	 * @return boolean
	 */
	public static boolean isPhoneNum(String phone) {

		Pattern pattern = Pattern.compile("^((1[0-9][0-9]))\\d{8}$");
		Matcher m = pattern.matcher(phone);

		return m.matches();

	}
	
	

	/**
	 * 是否为手机号(精确匹配---用时注意有可能会增加号段)
	 * 
	 * @param phone
	 * @return
	 */
	public static boolean ismobiles(String phone) {

		Pattern pattern = Pattern.compile("^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}|17[0-9]{9}$|18[0-9]{9}$");
		Matcher m = pattern.matcher(phone);

		return m.matches();

	}
	
	/**
	 * 是否为qq号(
	 * 
	 * @param qq
	 * @return
	 */
	public static boolean isQQ(String qq) {

		Pattern pattern = Pattern.compile("^[1-9][0-9]{5,10}");
		Matcher m = pattern.matcher(qq);

		return m.matches();

	}
	
	
	
	
	/**
	 * 是否为银行卡号(16-19位)
	 * 
	 * @param bank
	 * @return
	 */
	public static boolean isBank(String bank) {
		
		if(bank.length()==0){
			return false;
		}

		Pattern pattern = Pattern.compile("^(?!0+(?:\\.0+)?$)(?:[1-9]\\d{9,29}|0)?$");
		Matcher m = pattern.matcher(bank);

		return m.matches();

	}

	/**
	 * 去除字符串中的空格、回车、换行符、制表符
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String string) {
		String text = "";
		if (string != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(string);
			text = m.replaceAll("");
		}
		return text;
	}

	/**
	 * 用正则表达式去掉字符串中标点符号及其他一些特殊符号的方法
	 * 
	 * @param str
	 * @return
	 */
	public static boolean replaceCharacter(String string) {
		String text_0 = "";
		String text_1 = "";
		if (string != null) {

			if (string.replace("\\\\", "").length() == 0) {
				return false;
			}

			if (("\\" + string).replace("\\\\", "").length() == 0) {
				return false;
			}

			if (replaceBlank(string).length() == 0) {
				return false;
			}
			if (string
					.replaceAll(
							"[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]",
							"").length() == 0) {

				return false;
			}

			text_0 = string.replace("\\\\", "");

			text_1 = ("\\" + string).replace("\\\\", "");

			if (replaceBlank(text_0).length() == 0) {
				return false;
			}

			if (replaceBlank(text_1).length() == 0) {
				return false;
			}

			if (replaceBlank(text_0)
					.replaceAll(
							"[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]",
							"").length() == 0) {

				return false;
			}

			if (replaceBlank(text_1)
					.replaceAll(
							"[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]",
							"").length() == 0) {

				return false;
			}

			return true;
		}
		return false;
	}

	/**
	 * 程序是否在前台运行
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean isAppOnForeground(Context context) {
		// Returns a list of application processes that are running on the
		// device

		ActivityManager activityManager = (ActivityManager) context
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		String packageName = context.getApplicationContext().getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 判断应用是否在运行
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean isAppRunning(Context context, String packageName) {

		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		List<RunningTaskInfo> list = am.getRunningTasks(100);

		boolean isAppRunning = false;

		String MY_PKG_NAME = packageName;

		for (RunningTaskInfo info : list) {

			if (info.topActivity.getPackageName().equals(MY_PKG_NAME)
					|| info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {

				isAppRunning = true;

				Log.i("UTILS--->", info.topActivity.getPackageName()
						+ " info.baseActivity.getPackageName()="
						+ info.baseActivity.getPackageName());
				break;
			}

		}
		return isAppRunning;

	}

	/**
	 * float相乘
	 * 
	 * @param f1
	 * @param f2
	 * @return float
	 */
	public static float twofloatResult(float f1, float f2) {
		int m = 0;
		String s1 = "" + f1;
		String s2 = "" + f2;
		m += s1.split("\\.")[1].length();
		m += s2.split("\\.")[1].length();
		return (float) (Float.parseFloat(s1.replace(".", ""))
				* Float.parseFloat(s2.replace(".", "")) / Math.pow(10, m));
	}

	/**
	 * float精确到小数点后1位
	 * 
	 * @param fl
	 *            float
	 * @return String
	 */
	public static String Adecimal(float fl) {
		try {
			DecimalFormat fnum = new DecimalFormat("##0.0");
			String dd = fnum.format(fl);

			return dd;

		} catch (Exception e) {
			return "0.0";
		}

	}

	/**
	 * float精确到小数点后1位
	 * 
	 * @param fl
	 *            String
	 * @return String
	 */
	public static String Adecimal(String num) {
		try {
			float fl = Float.parseFloat(num);

			DecimalFormat fnum = new DecimalFormat("##0.0");
			String dd = fnum.format(fl);

			return dd;
		} catch (Exception e) {
			return "0.0";
		}

	}

	/**
	 * float精确到小数点后两位
	 * 
	 * @param fl
	 *            String
	 * @return String
	 */
	public static String bigDecimals(String num) {

		return new BigDecimal(num).setScale(2, BigDecimal.ROUND_HALF_UP) + "";
		// try {
		// float fl=Float.parseFloat(num);
		//
		// DecimalFormat fnum = new DecimalFormat("##0.00");
		// String dd = fnum.format(fl);
		//
		// return dd;
		// } catch (Exception e) {
		// return "0.00";
		// }

	}

	/**
	 * float精确到小数点后两位
	 * 
	 * @param fl
	 *            float
	 * @return String
	 */
	public static String bigDecimals(float fl) {
		try {
			DecimalFormat fnum = new DecimalFormat("##0.00");
			String dd = fnum.format(fl);

			return dd;

		} catch (Exception e) {
			return "0.00";
		}

	}

	/**
	 * List<String>去重
	 * 
	 * @param list
	 * @return List<String>
	 */
	public static List<String> removeDuplicate(List<String> list) {
		HashSet<String> h = new HashSet<String>(list);
		list.clear();
		list.addAll(h);
		return list;
	}
	
	/**
	 * List<HashMap<String, Object>> 去重
	 * @param list List<HashMap<String, Object>>
	 * @return List<HashMap<String, Object>>
	 */
	public static List<HashMap<String, Object>> removeDuplicateMap(List<HashMap<String, Object>> list) {
		
		
		List<HashMap<String,Object>> listMap2 = new LinkedList<HashMap<String,Object>>();  
        @SuppressWarnings("rawtypes")
		Set<HashMap> setMap = new HashSet<HashMap>();  
        for(HashMap<String,Object> map1 : list){  
            if(setMap.add(map1)){  
                listMap2.add(map1);  
            }  
        }  
		return listMap2;
		
		
	}
	
	/**
	 * 
	 * byte[]转为HashMap
	 * 
	 * @param bytes
	 * @return HashMap
	 */
	@SuppressWarnings("unchecked")
	public static HashMap<String, ?> bytesToMap(byte[] bytes) {
		HashMap<String, ?> result = null;
		try {
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
					bytes);
			ObjectInputStream inputStream = new ObjectInputStream(
					byteArrayInputStream);

			result = (HashMap<String, ?>) inputStream.readObject();
			inputStream.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 
	 * HashMap转为byte[]
	 * 
	 * @param map
	 * @return byte[]
	 */
	public static byte[] mapToBytes(HashMap<String, ?> map) {
		byte[] bytes = null;
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream outputStream = new ObjectOutputStream(
					byteArrayOutputStream);

			outputStream.writeObject(map);
			outputStream.close();

			bytes = byteArrayOutputStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}

	/**
	 * 
	 * list转成String
	 * 
	 * @param list
	 * @return String
	 */
	public static String listString(List<?> list) {

		try {

			// 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
					3000);
			// 然后将得到的字符数据装载到ObjectOutputStream
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(
					byteArrayOutputStream);
			// writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
			objectOutputStream.writeObject(list);
			// 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
			String listString = new String(Base64.encodeToString(
					byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
			// 关闭objectOutputStream
			objectOutputStream.close();
			byteArrayOutputStream.close();
			return listString;

		} catch (IOException e) {
			return "false";
		}
	}

	/**
	 * String 转成 list
	 * 
	 * @param listString
	 * @return List<?>
	 */
	public static List<?> stringList(String listString) {

		try {

			byte[] mobileBytes = Base64.decode(listString.getBytes(),
					Base64.DEFAULT);
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
					mobileBytes);
			ObjectInputStream objectInputStream = new ObjectInputStream(
					byteArrayInputStream);

			List<?> list = (List<?>) objectInputStream.readObject();
			objectInputStream.close();
			byteArrayInputStream.close();
			return list;
		} catch (StreamCorruptedException e) {
			return null;
		} catch (IOException e) {
			return null;
		} catch (ClassNotFoundException e) {
			return null;
		}
	}

	/**
	 * 定义分割常量 （#在集合中的含义是每个元素的分割，|主要用于map类型的集合用于key与value中的分割）
	 */
	private static final String SEP1 = "#";
	private static final String SEP2 = "|";

	/**
	 * Map转换String
	 * 
	 * @param map
	 *            :需要转换的Map
	 * @return String转换后的字符串
	 */
	public static String MapToString(Map<?, ?> map) {
		StringBuffer sb = new StringBuffer();
		// 遍历map
		for (Object obj : map.keySet()) {
			if (obj == null) {
				continue;
			}
			Object key = obj;
			Object value = map.get(key);
			if (value instanceof List<?>) {
				sb.append(key.toString() + SEP1 + listString((List<?>) value));
				sb.append(SEP2);
			} else if (value instanceof Map<?, ?>) {
				sb.append(key.toString() + SEP1
						+ MapToString((Map<?, ?>) value));
				sb.append(SEP2);
			} else {
				sb.append(key.toString() + SEP1 + value.toString());
				sb.append(SEP2);
			}
		}
		return "M" + encodeBase64(sb.toString());
	}

	/**
	 * String转换Map
	 * 
	 * @param mapText
	 *            :需要转换的字符串
	 * @param KeySeparator
	 *            :字符串中的分隔符每一个key与value中的分割
	 * @param ElementSeparator
	 *            :字符串中每个元素的分割
	 * @return Map<?,?>
	 */
	public static Map<String, Object> StringToMap(String mapText) {

		if (mapText == null || mapText.equals("")) {
			return null;
		}
		mapText = mapText.substring(1);

		mapText = decodeBase64(mapText);

		Map<String, Object> map = new HashMap<String, Object>();
		String[] text = mapText.split("\\" + SEP2); // 转换为数组
		for (String str : text) {
			String[] keyText = str.split(SEP1); // 转换key与value的数组
			if (keyText.length < 1) {
				continue;
			}
			String key = keyText[0]; // key
			String value = keyText[1]; // value
			if (value.charAt(0) == 'M') {
				Map<?, ?> map1 = StringToMap(value);
				map.put(key, map1);
			} else if (value.charAt(0) == 'L') {
				List<?> list = stringList(value);
				map.put(key, list);
			} else {
				map.put(key, value);
			}
		}
		return map;
	}

	/**
	 * 编码
	 * 
	 * @param cookieStr
	 * @return
	 */
	public static String encodeBase64(String cookieStr) {

		try {
			cookieStr = new String(Base64.encode(cookieStr.getBytes("UTF-8"),
					Base64.DEFAULT));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cookieStr;
	}

	/**
	 * 解码
	 * 
	 * @param cookieStr
	 * @return
	 */
	public static String decodeBase64(String cookieStr) {
		cookieStr = new String(Base64.decode(cookieStr.getBytes(),
				Base64.DEFAULT));
		return cookieStr;
	}

	
	/**
	 * 是否开启GPS权限
	 * @param context
	 * @return
	 */
	public static boolean locationState(Context context) {

		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	
	/**
	 * 是否开启Camera权限
	 * @param context
	 * @return
	 */
	public static boolean cameraState(Context context) {

			
			return false;
	}
	
	
	/**
	 * 泛型ArrayList转数组
	 * @param cls
	 * @param items
	 * @return
	 */
	@SuppressWarnings("unchecked")
    public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {
        if (items == null || items.size() == 0) {
            return (T[]) Array.newInstance(cls, 0);
        }
        return items.toArray((T[]) Array.newInstance(cls, items.size()));
    }
	
	
	
	/** 验证8位字母和数字 */
	public static boolean isLetter(String str) {
		Pattern p = Pattern.compile("^[A-Za-z0-9]{8}$");
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * 验证数字
	 * 
	 * @param str
	 * @param number 位数
	 * @return
	 */
	public static boolean isNumber(String str, int number) {
		String pattern = "^[0-9]{%s}$";
		Pattern p = Pattern.compile(String.format(pattern, number));
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * 验证至少几位以上数字
	 * 
	 * @param str 要验证的字符串
	 * @param number 位数
	 * @return
	 */
	public static boolean isNumberMore(String str, int number) {
		String pattern = "^[0-9]{%s,}$";
		Pattern p = Pattern.compile(String.format(pattern, number));
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	/**
	 * 验证是否为邮件格式
	 * @param strEmail
	 * @return
	 */
	public static boolean isEmail(String strEmail) {
		String strPattern = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strEmail);
		return m.matches();
	}
	
	
	
	/** 
	 * 方法名称:transMapToString 
	 * 传入参数:map 
	 * 返回值:String 形如 username'chenziwen^password'1234 
	*/  
	@SuppressWarnings("rawtypes")
	public static String transMapToString(TreeMap<String, String> map){  
	  Entry entry;  
	  StringBuffer sb = new StringBuffer();  
	  Iterator iterator = map.entrySet().iterator(); 
	  while(iterator.hasNext()) 
	  {  
		  entry = (Entry)iterator.next();  
	      sb.append(entry.getKey().toString()).append( "=" ).append(null==entry.getValue()?"":  
	      entry.getValue().toString()).append (iterator.hasNext() ? "&" : "");  
	      
	  }  
	  return sb.toString();  
	}  
	
	
	
	/** 
	 * 方法名称:translistToString 
	 * 传入参数:map 
	 * 返回值:String 形如 username'chenziwen^password'1234 
	*/  
	@SuppressWarnings("rawtypes")
	public static String translistToString(List<String> list){  
		
		StringBuffer sb=new StringBuffer();
		Iterator iterator = list.iterator(); 
		while(iterator.hasNext()) 
		{  
			sb.append(iterator.next()).append(iterator.hasNext() ? "," : "");
			
		}  
		
		return sb.toString();  
	}  

	
	/**
	 * 栈实现钱币显示问题，逗号分隔三位
	 * 处理字串型 
	 * @param str
	 * @return
	 */
	public static String strFormatMoney(String str){ 
		Stack<Character> sta =new Stack<Character>(); 
		StringBuffer sb=new StringBuffer(); 
		char[] charstr=str.toCharArray(); 
		for(char a:charstr){ 
			sta.push(a); 
		} 
		Stack<String> type= new Stack<String>(); 
		int i=0; 
		while(!sta.empty()){ 
			if(i%4==0){ 
				type.push(","); 
			} else { 
				type.push(sta.pop().toString()); 
			} 
			i++; 
		} 
		while(!type.empty()){ 
			String s=type.pop(); 
			sb.append(s); 
		} 
		String fs=sb.toString().substring(0,sb.toString().lastIndexOf(",")); 
		return fs; 
	}
	
	
	/**
	 * 栈实现钱币显示问题，逗号分隔三位
	 * 处理长整形  
	 * @param str
	 * @return
	 */
	public static String strFormatMoney(Long l){ 
		String str=String.valueOf(l); 
		Stack<Character> sta =new Stack<Character>(); 
		StringBuffer sb=new StringBuffer(); 
		char[] charstr=str.toCharArray(); 
		for(char a:charstr){ 
			sta.push(a); 
		} 
		Stack<String> type= new Stack<String>(); 
		int i=0; 
		while(!sta.empty()){ 
			if(i%4==0){ 
				type.push(","); 
			} else { 
				type.push(sta.pop().toString()); 
			} 
			i++; 
		} 
		while(!type.empty()){ 
			String s=type.pop(); 
			sb.append(s); 
		} 
		String fs=sb.toString().substring(0,sb.toString().lastIndexOf(",")); 
		return fs; 
	} 
	
	/**
	 * 栈实现钱币显示问题，逗号分隔三位
	 * 处理整形  
	 * @param str
	 * @return
	 */
	public static String strFormatMoney(int l){ 
		String str=String.valueOf(l); 
		Stack<Character> sta =new Stack<Character>(); 
		StringBuffer sb=new StringBuffer(); 
		char[] charstr=str.toCharArray(); 
		for(char a:charstr){ 
			sta.push(a); 
		} 
		Stack<String> type= new Stack<String>(); 
		int i=0; 
		while(!sta.empty()){ 
			if(i%4==0){ 
				type.push(","); 
			} else { 
				type.push(sta.pop().toString()); 
			} 
			i++; 
		} 
		while(!type.empty()){ 
			String s=type.pop(); 
			sb.append(s); 
		} 
		String fs=sb.toString().substring(0,sb.toString().lastIndexOf(",")); 
		return fs; 
	} 
	
	
	/**
	 * 将字符串转成字符串数组
	 * @param str
	 * @return
	 */
	public static String[] spitStr(String str){
		
		char [] stringArr = str.toCharArray(); //注意返回值是char数组
		String[] result=new String[stringArr.length];

		for (int i = 0; i < stringArr.length; i++) {
			
			result[i]=String.valueOf(stringArr[i]);
			
		}
		
		return result;
	}
	
	
	/**
	 * 去掉字符串中匹配 的字符串 
	 * @param regex  要替换的内容 
	 * @param value  字符串
	 * @param state  替换的内容变成什么
	 * @return
	 */
	public static String toRegex(String regex, String value, String state) { 
		Pattern p = Pattern.compile(regex); 
		Matcher m = p.matcher(value); 
		StringBuffer sb = new StringBuffer(); 
		while (m.find()) { 
			m.appendReplacement(sb, state); 
		} 
		m.appendTail(sb); 
		return sb.toString(); 
	}


		/**
		 * 判定输入汉字
		 * @param c
		 * @return
		 */
		public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
		     || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
		    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
		    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
		    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
		    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
		    return true;
		}
		return false;
		}
		
		/**
		 * 检测String是否全是中文
		 * @param name
		 * @return
		 */
		public static boolean checkNameChese(String name)
		{
		   boolean res=true;
		   char [] cTemp = name.toCharArray(); 
		   for(int i=0;i<name.length();i++)
		   {
		           if(!isChinese(cTemp[i]))
		           {
		                   res=false;
		                   break;
		           }
		   }           
		   return res;
		}
		
		
}
